//
//  AddressBookVC.m
//  easyTaxi
//
//  Created by ellenpage on 12-12-18.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#import "Constant.h"
#import "AddressBookVC.h"
#import "BMapKit.h"
#import "BMKMapView.h"
#import "PassMapValue.h"
#import "ConfirmAddressView.h"
#import "PassValueClass.h"
#import "MBProgressHUD.h"
#import "GetPhoneInfo.h"
#import "ViewAnimation.h"
#import "AddressBookCell.h"

CGRect bottomRect = CGRectMake(0, iP5 ? 445 :361, 320, 65);
CGRect topRect    = CGRectMake(0, 0,  320, 44);
CGRect searchRect = CGRectMake(0, 44, 320, 44);

@interface AddressBookVC ()<UINavigationControllerDelegate,BMKMapViewDelegate,BMKGeneralDelegate,BMKSearchDelegate,BMKAnnotation,UISearchBarDelegate,UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property (retain, nonatomic) BMKMapView *mapView;

@property (retain, nonatomic) BMKPointAnnotation  *myPosition;  //自己位置标注

@property (strong, nonatomic) IBOutlet UISearchBar *addressSearchBar;
@property (strong, nonatomic) IBOutlet UIView *bottomView;

@property (strong, nonatomic) IBOutlet UILabel *currentLocationLbl;

@property (strong, nonatomic) IBOutlet UITextField *nameTextField;
@property (strong, nonatomic) IBOutlet UIView *topView;
@property (strong, nonatomic) IBOutlet UIView *searchBarView;

@property (strong, nonatomic) IBOutlet UIView *addressListView;

@property (retain, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) IBOutlet UITableView *addressTBView;

@property (retain, nonatomic) BMKSearch      *POISearcher; //搜索poi信息
@property (retain, nonatomic) BMKPoiResult   *resultpoi;   //搜索结果
@property (retain, nonatomic) BMKSearch      *search;      //根据坐标 逆地理编码
@property (retain, nonatomic) BMKAddrInfo    *bmkInfo;     //地址信息

@property (retain, nonatomic) NSString *latestTimeStamp;

- (IBAction)showAddressList;

- (IBAction)hideAddressList;

- (IBAction)goBack;

- (IBAction)addThisAddress;

@end

@implementation AddressBookVC

#pragma mark - GoBack - 返回

- (IBAction)goBack
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - System Function - 系统函数

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self){
    }
    return self;
}

- (void)viewDidLoad
{
    [self initialMap];
    [self initialData];
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [self setAddressSearchBar:nil];
    [self setBottomView:nil];
    [self setCurrentLocationLbl:nil];
    [self setNameTextField:nil];
    [self setTopView:nil];
    [self setSearchBarView:nil];
    [self setAddressListView:nil];
    [self setDataArray:nil];
    [self setAddressTBView:nil];
    [self setLatsetTimeLbl:nil];
    [super viewDidUnload];
}

- (void)initialMap
{
    self.mapView = [[BMKMapView alloc] init];
    self.mapView.frame = CGRectMake(0, 0, 320, 430);
    self.mapView.showsUserLocation = YES;
    self.mapView.delegate = self;

    [self.view insertSubview:self.mapView atIndex:0];
    
    self.myPosition = [[BMKPointAnnotation alloc] init];
}

- (void)initialData
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getEndAddressNotiAddresslist) name:kGetEndAddressNoti_Addresslist object:nil];
    self.bottomView.backgroundColor       = [[UIColor darkTextColor] colorWithAlphaComponent:0.65];
    self.addressSearchBar.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.65];
    
    [self.view addSubview:self.topView];
    [self.view addSubview:self.searchBarView];
    [self.view addSubview:self.bottomView];

    self.dataArray   = [NSMutableArray array];
    self.POISearcher = [[BMKSearch alloc] init];
    self.POISearcher.delegate = self;

    [self.view addSubview:self.addressListView];
    self.addressListView.hidden = YES;
    
    self.addressTBView.delegate   = self;
    self.addressTBView.dataSource = self;
    
    self.bottomView.frame     = bottomRect;
    self.topView.frame        = topRect;
    self.searchBarView.frame  = searchRect;
}

- (void)getEndAddressNotiAddresslist
{    
    [self addPin];    //插大头针
    [self getAddress];//反编译地址
}

#pragma mark - SearchBar Delegate - UISearchBar 代理

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self.bottomView setFrame:CGRectMake(0, 147, 320, 65)];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.addressSearchBar resignFirstResponder];
    [self.bottomView setFrame:CGRectMake(0, 351, 320, 65)];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.addressSearchBar resignFirstResponder];
    [self.bottomView setFrame:CGRectMake(0, 351, 320, 65)];
    
    //如果没有输入地址
    if (_addressSearchBar.text == nil)
    {
        UIAlertView *noAddressAlert = [[UIAlertView alloc] initWithTitle:@"请先至少输入一个目的地"
                                                                 message:nil
                                                                delegate:self
                                                       cancelButtonTitle:@"知道了"
                                                       otherButtonTitles:nil, nil];
        [noAddressAlert show];
    }
    else
    {
        NSString *cityStr = [PassValueClass sharedIntance].cityStr;
        NSString *keyStr  = [NSString stringWithFormat:@"%@",_addressSearchBar.text];
        [_POISearcher poiSearchInCity:cityStr withKey:keyStr pageIndex:0];//开始搜索poi地址
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
}

- (void)onGetPoiResult:(NSArray *)poiResultList searchType:(int)type errorCode:(int)error
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    if (error == BMKErrorOk)
    {
        _resultpoi = [poiResultList objectAtIndex:0];
        if (_resultpoi.poiInfoList.count > 0)//如果有数据返回
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsFromAddressListView];//地址簿,确认地址试图

            ConfirmAddressView *addressResultView = [[ConfirmAddressView alloc] init];
            addressResultView.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.65];

            [self.view addSubview:addressResultView];
            addressResultView.resultpoi = _resultpoi;
            
            [addressResultView.addressResultTBView reloadData];
        }
        else
        {
            UIAlertView *noAddressAlert=[[UIAlertView alloc] initWithTitle:@"出错"
                                                                   message:@"地图目前没有您选择的目的地"
                                                                  delegate:self
                                                         cancelButtonTitle:@"好的"
                                                         otherButtonTitles:nil];
            [noAddressAlert show];
        }
    }
    else
    {
        UIAlertView *noAddressAlert=[[UIAlertView alloc] initWithTitle:@"出错"
                                                               message:@"地图目前没有您选择的目的地"
                                                              delegate:self
                                                     cancelButtonTitle:@"好的"
                                                     otherButtonTitles:nil];
        [noAddressAlert show];
    }
}

#pragma mark - TextField Delegate - TextField 代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"])
    {
        [_nameTextField resignFirstResponder];
        [_bottomView setFrame:CGRectMake(0, 351, 320, 65)];
        return NO;
    }  
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [_addressSearchBar resignFirstResponder];
    [_bottomView setFrame:CGRectMake(0, 147, 320, 65)];
                                                
}

- (IBAction)addThisAddress//加入这个地址
{
    if (_currentLocationLbl.text == nil)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请先输入一个目的地"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"确定", nil];
        [alert show];
    }
    else
    {
        [_nameTextField resignFirstResponder];
        [_bottomView setFrame:CGRectMake(0, 351, 320, 65)];
        
        [self saveThisAddress];//存入数据库
        
        _currentLocationLbl.text = nil;
        _addressSearchBar.text   = nil;
        _nameTextField.text      = nil;
    }
}

- (void)saveThisAddress
{    
    BMKPoiInfo *tmpPoi = [PassValueClass sharedIntance].poi;
    
    NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults]objectForKey:kMyAddressBook]];
    
    if (dict == nil)
    {
        dict = [NSMutableDictionary dictionary];
    }
    
    NSArray *array = [dict objectForKey:kAddressBookArray];
    NSMutableArray *mArray = [NSMutableArray arrayWithArray:array];
    
    NSMutableDictionary *tmpDict = [NSMutableDictionary dictionary];

    NSString *poiName  = _currentLocationLbl.text;
    NSString *areaCode = [PassValueClass sharedIntance].areaCode;
    NSString *latStr   = [NSString stringWithFormat:@"%f",tmpPoi.pt.latitude];
    NSString *longStr  = [NSString stringWithFormat:@"%f",tmpPoi.pt.longitude];
    
    NSString *nameStr;
    if (_nameTextField.text == nil)
    {
        nameStr = tmpPoi.name;
    }
    else
    {
        nameStr = _nameTextField.text;
    }

    NSString *timeStr = [GetPhoneInfo getCurrentTimeStamp];
    
    [tmpDict setObject:poiName  forKey:kPoiName];
    [tmpDict setObject:areaCode forKey:kAreaCode];
    [tmpDict setObject:nameStr  forKey:kAddressName];
    [tmpDict setObject:latStr   forKey:kLatitude];
    [tmpDict setObject:longStr  forKey:kLongitude];
    [tmpDict setObject:timeStr  forKey:kLastTime];
    
    for (int i = 0; i<mArray.count; i++)
    {
        NSMutableDictionary *tmpdict = [mArray objectAtIndex:i];
        if ([tmpdict isEqual:dict])
        {
            return;
        }
    }
    
    [mArray insertObject:tmpDict atIndex:0];
    NSLog(@"mArray = %@",mArray);
    
    [dict setObject:mArray forKey:kAddressBookArray];
    NSLog(@"dict   = %@",dict);

    [dict setObject:timeStr forKey:kAddressBookTimeStamp];
    NSLog(@"dict   = %@",dict);

    NSLog(@"%@--%@",timeStr,[self timeStr:timeStr]);
    _latsetTimeLbl.text = [NSString stringWithFormat:@"%@",[self timeStr:timeStr]];
    
    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kMyAddressBook];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)timeStr:(NSString *)str
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    NSDate *confromTimesp      = [NSDate dateWithTimeIntervalSince1970:[str integerValue]];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}

#pragma mark - MapView Delegate - MapView代理

- (void)addPin
{
    BMKPoiInfo *tmpPoi = [PassValueClass sharedIntance].poi;
    CLLocationCoordinate2D coor;
    coor.latitude  = tmpPoi.pt.latitude;
    coor.longitude = tmpPoi.pt.longitude;

    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc]init];
    annotation.coordinate = coor;
    [_mapView addAnnotation:annotation];
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]])
    {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation
                                                                                   reuseIdentifier:@"myAnnotation"];
        
        newAnnotationView.pinColor = BMKPinAnnotationColorRed;
        newAnnotationView.animatesDrop = YES;
        return newAnnotationView;
    }
    return nil;
}


- (void)getAddress
{
    if (!_search)
    {
        _search = [[BMKSearch alloc] init];
        _search.delegate = self;
    }
    
    BMKPoiInfo *tmpPoi = [PassValueClass sharedIntance].poi;
    CLLocationCoordinate2D pt = tmpPoi.pt;

    [_mapView setCenterCoordinate:pt animated:YES];
    
    [_search reverseGeocode:pt];
}

- (void)onGetAddrResult:(BMKAddrInfo*)result errorCode:(int)error
{
    _bmkInfo = result;
    NSString *addressStr = result.strAddr;
    NSLog(@"%@",addressStr);
    _currentLocationLbl.text = addressStr;
}

#pragma mark - ShowAndHideAddressList - 打开隐藏地址列表

- (IBAction)showAddressList
{
    _addressListView.hidden = NO;
    [ViewAnimation viewAnimation:0 view:_addressListView];
    [self refreshTableView];//刷新TBView
}

- (IBAction)hideAddressList
{
    NSArray *views = [self.view subviews];
    UIView *tmpView;
    for(tmpView in views)
    {
        [tmpView resignFirstResponder];
    }
    
    [ViewAnimation viewAnimation:1 view:_addressListView];
    _addressListView.hidden = YES;
}

- (void)refreshTableView
{
    [_nameTextField resignFirstResponder];
    [_addressSearchBar resignFirstResponder];
    
    NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults]objectForKey:kMyAddressBook]];
    
    NSArray      *array      = [dict objectForKey:kAddressBookArray];
    NSString     *timeStamp  = [dict objectForKey:kAddressBookTimeStamp];

    NSLog(@"array = %@",array);
    
    _dataArray = [NSMutableArray arrayWithArray:array];
    
    NSLog(@"_dataArray = %@",_dataArray);

    _latestTimeStamp = timeStamp;
    
    [_addressTBView reloadData];
}

#pragma mark - TBView Delegate - TBView代理

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 121;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [_dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddressBookCell"];
    if (!cell)
    {
        cell = [AddressBookCell getInstance];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (_dataArray > 0)
    {
        cell.locateBtn.tag = indexPath.row;
        cell.deleteBtn.tag = indexPath.row;
        cell.renameBtn.tag = indexPath.row;

        NSDictionary *dict = [_dataArray objectAtIndex:indexPath.row];
        
        NSString *name = [dict objectForKey:kAddressName];
        cell.nameTxtField.text = name;
        
        NSString *poiName = [dict objectForKey:kPoiName];
        cell.locationTxtField.text = poiName;
        
        [cell.locateBtn addTarget:self action:@selector(locatePosition:) forControlEvents:UIControlEventTouchUpInside];
        [cell.deleteBtn addTarget:self action:@selector(deleteThisAddress:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}

- (void)locatePosition:(UIButton *)sender
{
    int i = sender.tag;
    
    NSDictionary *dict    = [[NSUserDefaults standardUserDefaults] objectForKey:kMyAddressBook];
    NSArray      *array   = [dict objectForKey:kAddressBookArray];
    NSDictionary *tmpDict = [array objectAtIndex:i];

    _addressListView.hidden = YES;

    float lat = [[tmpDict objectForKey:kLatitude]  floatValue];
    float lng = [[tmpDict objectForKey:kLongitude] floatValue];
    
    CLLocationCoordinate2D coor;
    coor.latitude  = lat;
    coor.longitude = lng;
    
    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc]init];
    annotation.coordinate = coor;
    
    [_mapView setCenterCoordinate:coor animated:YES];
    [_mapView addAnnotation:annotation];
}

- (void)deleteThisAddress:(UIButton *)sender
{
    int i = sender.tag;
    NSLog(@"%d",i);
    
    NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults]objectForKey:kMyAddressBook]];
    
    NSLog(@"dict = %@",dict);
    
    NSArray        *array  = [dict objectForKey:kAddressBookArray];
    NSMutableArray *mArray = [NSMutableArray arrayWithArray:array];
    [mArray removeObjectAtIndex:i];
    NSLog(@"mArray = %@",mArray);
    
    NSString *str = [GetPhoneInfo getCurrentTimeStamp];
    NSLog(@"str = %@",str);
    
    [dict setObject:str    forKey:kAddressBookTimeStamp];
    if (mArray.count == 0)
    {
        mArray = [NSMutableArray array];
        [dict setObject:mArray forKey:kAddressBookArray];
    }
    else
    {
        [dict setObject:mArray forKey:kAddressBookArray];
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kMyAddressBook];
    
    [self refreshTableView];
}

@end
